package com.sec.android.app.myfiles.module.local.category;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;

import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.AbsContentObserverImp;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.util.FileUtils;

/**
 * Created by jaebae on 2016-01-12.
 */
public class MediaProviderObserver extends ContentObserver {
    ContentResolver mContentResolver;
    AbsContentObserverImp mListener;
    Uri mProviderUri;

    private static final long INTERVAL = 500;

    /**
     * Creates a content observer.
     *
     * @param handler The handler to run {@link #onChange} on, or null if none.
     */
    public MediaProviderObserver(Context context, AbsContentObserverImp listener, Handler handler, FileRecord targetRecord) {
        super(handler);
        mContentResolver = context.getContentResolver();
        mListener = listener;
        mProviderUri = getUri(targetRecord);
    }

    public void start() {
        mContentResolver.registerContentObserver(mProviderUri, false, this);
    }

    private Uri getUri(FileRecord targetRecord) {
        Uri ret = FileUtils.MEDIA_PROVIDER_URI;

        if (targetRecord instanceof CategoryFileRecord) {
            CategoryFileRecord record = (CategoryFileRecord) targetRecord;
            switch (record.getCategoryType()) {
                case Image:
                    ret = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    break;
                case Video:
                    ret = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    break;
                case Audio:
                    ret = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    break;
                default:
                    break;
            }
        }

        return ret;
    }

    public void stop() {
        mContentResolver.unregisterContentObserver(this);
    }

    @Override
    public void onChange(boolean selfChange) {
        Log.d(this, "onChange");
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, INTERVAL);
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Log.d("MediaProviderObserver", "Handler call mListener.onEvent");
            mListener.onEvent(0);
            return true;
        }
    });
}
